package dji.ux.ext.widget.gimbal;

import androidx.annotation.NonNull;

import dji.common.gimbal.Attitude;
import dji.keysdk.DJIKey;
import dji.keysdk.GimbalKey;
import dji.thirdparty.io.reactivex.Flowable;
import dji.ux.beta.base.DJISDKModel;
import dji.ux.beta.base.WidgetModel;
import dji.ux.beta.base.uxsdkkeys.ObservableInMemoryKeyedStore;
import dji.ux.beta.util.DataProcessor;
import dji.ux.beta.util.SettingDefinitions;

/**
 * Widget Model for the {@link GimbalPitchWidget} used to define
 * the underlying logic and communication
 */
public class GimbalPitchWidgetModel extends WidgetModel {

    private final DataProcessor<Float> gimbalPitchProcess;
    private final DataProcessor<Attitude> gimbalAttitudeProcess;
    private int cameraIndex;

    public GimbalPitchWidgetModel(@NonNull DJISDKModel djiSdkModel,
                                  @NonNull ObservableInMemoryKeyedStore keyedStore) {
        super(djiSdkModel, keyedStore);
        this.cameraIndex = SettingDefinitions.CameraIndex.CAMERA_INDEX_0.getIndex();
        gimbalAttitudeProcess = DataProcessor.create(new Attitude(0, 0, 0));
        gimbalPitchProcess = DataProcessor.create(0.0f);
    }

    /**
     * Get the pitch of the gimbal.
     *
     * @return Flowable for the DataProcessor that user should subscribe to.
     */
    public Flowable<Float> getGimbalPitch() {
        return gimbalPitchProcess.toFlowable();
    }

    /**
     * Get the camera index for which the model is reacting.
     *
     * @return int representing {@link SettingDefinitions.CameraIndex}.
     */
    @NonNull
    public SettingDefinitions.CameraIndex getCameraIndex() {
        return SettingDefinitions.CameraIndex.find(cameraIndex);
    }

    /**
     * Set camera index to which the model should react.
     *
     * @param cameraIndex index of the camera.
     */
    public void setCameraIndex(@NonNull SettingDefinitions.CameraIndex cameraIndex) {
        this.cameraIndex = cameraIndex.getIndex();
        restart();
    }

    @Override
    protected void inSetup() {
        DJIKey attitudeKey = GimbalKey.create(GimbalKey.ATTITUDE_IN_DEGREES, cameraIndex);
        bindDataProcessor(attitudeKey, gimbalAttitudeProcess, (attitude) -> {
            Attitude attitudeInDegree = (Attitude) attitude;
            if (attitudeInDegree != null) {
                gimbalPitchProcess.onNext(attitudeInDegree.getPitch());
            }
        });
    }

    @Override
    protected void inCleanup() {
        //Nothing to cleanup
    }

    @Override
    protected void updateStates() {
        //Nothing to update
    }
}
